package com.material.mdbook.exception;

import android.content.Context;
import android.content.Intent;
import android.util.Log;


public class CrashHandler implements Thread.UncaughtExceptionHandler {

    public static final String TAG = "CrashHandler";

    //系统默认的UncaughtException处理类   
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    //程序的Context对象  
    private Context mContext;


    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        //获取系统默认的UncaughtException处理器  
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为程序的默认处理器  
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        StringBuilder sb = new StringBuilder();
        sb.append("\n原因："+ex );
        sb.append("\n堆栈：");
        for (StackTraceElement stackTraceElement : ex.getStackTrace()) {
            Log.i("Exception",stackTraceElement.toString());
            sb.append("\n "+stackTraceElement + "");
        }
        ex.printStackTrace();
        Intent intent = new Intent(mContext, ShowExceptionActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("exception", sb.toString());
//        intent.putExtra("exception", ex);
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前

    }


}  